package org.ruiyichen.guizhou.agr.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.google.gson.reflect.TypeToken;
import com.louisgeek.dropdownviewlib.DropDownView;

import org.ruiyichen.guizhou.agr.R;
import org.ruiyichen.guizhou.agr.base.BaseActivity;
import org.ruiyichen.guizhou.agr.base.DataManger;
import org.ruiyichen.guizhou.agr.bean.DicEntity;
import org.ruiyichen.guizhou.agr.bean.Response;
import org.ruiyichen.guizhou.agr.bean.mode.LandModel;
import org.ruiyichen.guizhou.agr.config.Constant;
import org.ruiyichen.guizhou.agr.imp.IIrrigatedAreaFilter;
import org.ruiyichen.guizhou.agr.net.OkHttpManager;
import org.ruiyichen.guizhou.agr.ui.mineview.BToast;
import org.ruiyichen.guizhou.agr.utils.ClassUtils;
import org.ruiyichen.guizhou.agr.utils.ListUtil;
import org.ruiyichen.guizhou.agr.utils.StrUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 添加灌区
 */
public class AddIrrigatedAreaActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG_ID = "id";
    public static final int TO_SELECT_DEVICE = 1001;
    /**
     * 当前状态
     */
    private boolean isEdit = true;

    private DropDownView ddvAddIrrigatedSelectLand;
    private EditText etAddIrrigatedAreaName;

    private String[] selectDeviceIds;

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.df_activity_add_irrigated_area);
        bOkHttpManager = new OkHttpManager(this, bHandler);
        initData();
    }

    @Override
    protected void initViews() {
        setTitle("新建灌区").setRightImage(0).setRightText(null);
        etAddIrrigatedAreaName = findViewById(R.id.et_add_irrigated_area_name);
        ddvAddIrrigatedSelectLand = findViewById(R.id.ddv_add_irrigated_select_land);
        /*List<DicEntity.DicInfo> periodList = new ArrayList<>();
        periodList.add(new DicEntity.DicInfo("0", "地块1"));
        periodList.add(new DicEntity.DicInfo("1", "地块2"));
        periodList.add(new DicEntity.DicInfo("2", "地块3"));
        periodList.add(new DicEntity.DicInfo("3", "地块4"));
        ddvAddIrrigatedSelectLand.setupDataList(new ClassUtils<DicEntity.DicInfo>().objListToMapList(periodList));*/
    }

    @Override
    protected void initEvents() {
        findViewById(R.id.iv_normal_back).setOnClickListener(this);
        findViewById(R.id.tv_add_irrigated_area).setOnClickListener(this);
        final View tvNormalOther = findViewById(R.id.tv_normal_other);
        tvNormalOther.setOnClickListener(this);
        tvNormalOther.setEnabled(false);
        etAddIrrigatedAreaName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                boolean canSave = StrUtil.isNotEmpty(s.toString());
                setRightText(canSave ? "保存" : null);
                tvNormalOther.setEnabled(canSave);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_add_irrigated_area:
                if (StrUtil.isEmpty(ddvAddIrrigatedSelectLand.getSelectKey())) {
                    BToast.getInstance().show("请选择绑定地块~");
                    return;
                }
                //跳转默认设备页
                Intent it = new Intent(this, IrrigatedDeviceActivity.class);
                it.putExtra(IrrigatedDeviceActivity.TAG_TITLE, etAddIrrigatedAreaName.getText()
                        .toString());
                it.putExtra(IrrigatedDeviceActivity.TAG_ID, ddvAddIrrigatedSelectLand.getSelectKey());
                startActivityForResult(it, TO_SELECT_DEVICE);
                break;
            case R.id.tv_normal_other:
                //保存
                submit();
                break;
        }
    }

    private void initData() {
        Map<String, String> body = new HashMap<>();
        bOkHttpManager.httpRequest(Constant.RequestType.GET_ALL_LANDS, Constant.Http.GET, body,
                false, new TypeToken<Response<List<LandModel>, Void>>() {
                }.getType(), true, false);
    }


    /**
     * 提交
     */
    private void submit() {
        Map<String, Object> body = new HashMap<>();
        //landId	Integer	地块ID
        //irrigName	String	灌区名称
        body.put("landId", ddvAddIrrigatedSelectLand.getSelectKey());
        body.put("irrigName", etAddIrrigatedAreaName.getText()
                .toString());
        body.put("deviceIds", selectDeviceIds);
        bOkHttpManager.httpRequest(Constant.RequestType.UPDATE_ADD_IRRIGID, Constant.Http.POSTSTRING,
                body, false, new
                TypeToken<Response<Void, Void>>() {
                }.getType(), true, false);
    }

    @Override
    protected void onPostHandle(int requestType, Object response, boolean error, int errorCode, Object obj1, Object obj2) {
        super.onPostHandle(requestType, response, error, errorCode, obj1, obj2);
        if (error) {
            BToast.getInstance().show(getResources().getString(R.string.abnormal));
        } else {
            if (response == null) {
                BToast.getInstance().show(getResources().getString(R.string.datafailure));
            } else {
                if (requestType == Constant.RequestType.GET_ALL_LANDS) {
                    Response<List<LandModel>, Void> result = (Response<List<LandModel>, Void>) response;
                    if (result.isSuccess()) {
                        List<LandModel> landList = result.getData();
                        if (ListUtil.isNotEmpty(landList)) {
                            List<DicEntity.DicInfo> periodList = new ArrayList<>();
                            for (int i = 0; i < landList.size(); i++) {
                                periodList.add(new DicEntity.DicInfo(landList.get(i).landId,
                                        landList.get(i).landName));
                            }
                            ddvAddIrrigatedSelectLand.setupDataList(new ClassUtils<DicEntity.DicInfo>().objListToMapList(periodList));
                        }
                    } else {
                        BToast.getInstance().show(result.getMsg());
                    }
                } else if (requestType == Constant.RequestType.UPDATE_ADD_IRRIGID) {
                    Response<Void, Void> result = (Response<Void, Void>) response;
                    if (result.isSuccess()) {
                        finish();
                    }
                    BToast.getInstance().show(result.getMsg());
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == TO_SELECT_DEVICE) {
                selectDeviceIds = data.getStringArrayExtra(IrrigatedDeviceActivity
                        .SELECT_DEVICE_IDS);
            }
        }
    }
}
